#!/bin/bash

# 后端服务重启脚本
# 功能：检查并终止已有的Spring Boot进程，然后重新启动服务

echo "=== 招聘平台后端服务重启脚本 ==="

# 设置项目目录
PROJECT_DIR="/Users/jinxian/zhaoqi/zhaoqi_java"
cd "$PROJECT_DIR" || exit 1

# 强制终止所有相关进程
echo "正在强制终止所有相关进程..."

# 1. 终止所有Spring Boot相关进程
echo "终止Spring Boot进程..."
ps aux | grep "spring-boot:run" | grep -v grep | awk '{print $2}' | xargs -r kill -9 2>/dev/null
sleep 1

# 2. 终止所有Maven相关进程
echo "终止Maven进程..."
ps aux | grep "mvn.*spring-boot" | grep -v grep | awk '{print $2}' | xargs -r kill -9 2>/dev/null
sleep 1

# 3. 终止所有hr-outsourcing-platform相关Java进程
echo "终止相关Java进程..."
ps aux | grep "java.*hr-outsourcing-platform" | grep -v grep | awk '{print $2}' | xargs -r kill -9 2>/dev/null
sleep 1

# 4. 强制终止占用8080端口的所有进程
echo "强制终止占用8080端口的进程..."
lsof -ti:8080 | xargs -r kill -9 2>/dev/null
sleep 1

# 5. 再次检查并清理任何残留进程
echo "清理残留进程..."
pkill -9 -f "spring-boot:run" 2>/dev/null
pkill -9 -f "hr-outsourcing-platform" 2>/dev/null
sleep 1

echo "✅ 所有相关进程已强制终止"
echo ""

# 最终检查端口状态
if lsof -Pi :8080 -sTCP:LISTEN -t >/dev/null 2>&1; then
    echo "⚠️  端口8080仍被占用，进行最后清理..."
    lsof -ti:8080 | xargs -r kill -9 2>/dev/null
    sleep 2
fi

echo "✅ 端口8080已释放"
echo ""

# 编译项目
echo "正在编译项目..."
mvn clean compile -q
if [ $? -ne 0 ]; then
    echo "❌ 编译失败，请检查代码错误"
    exit 1
fi
echo "✅ 编译成功"
echo ""

# 启动服务
echo "正在启动Spring Boot服务..."
echo "启动命令: mvn spring-boot:run"
echo "服务将在 http://localhost:8080 启动"
echo "按 Ctrl+C 可停止服务"
echo ""
echo "=== 服务启动日志 ==="

# 启动服务并显示日志
mvn spring-boot:run

echo ""
echo "=== 服务已停止 ==="
